package com.pheruagor.handmanager.view {
    import com.pheruagor.handmanager.controller.CloseMemberEditionPopUpCommand;
    import com.pheruagor.handmanager.model.MemberEditionPopUpProxy;
    import com.pheruagor.handmanager.model.business.Person;
    import com.pheruagor.handmanager.utils.combobox.ComboboxUtils;
    import com.pheruagor.handmanager.view.component.MemberEditionPopUp;

    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.filesystem.File;
    import flash.net.FileFilter;

    import mx.events.FlexEvent;
    import mx.events.ListEvent;
    import mx.events.ValidationResultEvent;
    import mx.formatters.DateFormatter;
    import mx.validators.DateValidator;

    import org.puremvc.as3.patterns.mediator.Mediator;

    public class MemberEditionPopUpMediator extends Mediator {
        public static const NAME:String = "memberCreationPopUpMediator";

        //-----------------------------------------------------
        // Properties
        //-----------------------------------------------------
        [Bindable]
        [Embed(source="assets/man.png")]
        private var m_manLogo:Class;

        [Bindable]
        [Embed(source="assets/woman.png")]
        private var m_womanLogo:Class;

        private var m_proxy:MemberEditionPopUpProxy;
        private var m_dateFormatter:DateFormatter;

        //-----------------------------------------------------
        // Initialization
        //-----------------------------------------------------
        public function MemberEditionPopUpMediator(view:MemberEditionPopUp) {
            super(NAME, view);
        }


        //-----------------------------------------------------
        // IMediator Interface
        //-----------------------------------------------------
        override public function onRegister():void {
            m_dateFormatter = new DateFormatter();
            m_dateFormatter.formatString = "DD/MM/YYYY";
            memberCreationPopUp.addEventListener(FlexEvent.CREATION_COMPLETE, onMemberCreationPopUpCreationCompleted);
            m_proxy = MemberEditionPopUpProxy(facade.retrieveProxy(MemberEditionPopUpProxy.NAME));
        }

        override public function onRemove():void {
            memberCreationPopUp.okButton.removeEventListener(MouseEvent.CLICK, onOkButtonClicked);
            memberCreationPopUp.cancelButton.removeEventListener(MouseEvent.CLICK, onCancelButtonClicked);
            memberCreationPopUp.handComboBox.removeEventListener(ListEvent.CHANGE, onHandChanged);
            memberCreationPopUp.genderCombo.removeEventListener(ListEvent.CHANGE, onGenderChanged);
            memberCreationPopUp.subscriptionDateTextInput.removeEventListener(Event.CHANGE, onSubscriptionDateChanged);
            memberCreationPopUp.birthdayTextInput.removeEventListener(Event.CHANGE, onBirthdayChanged);
            memberCreationPopUp.sizeTextInput.removeEventListener(Event.CHANGE, onSizeChanged);
            memberCreationPopUp.lastnameTextInput.removeEventListener(Event.CHANGE, onLastnameChanged);
            memberCreationPopUp.fornameTextInput.removeEventListener(Event.CHANGE, onFornameChanged);
            memberCreationPopUp.removeEventListener(FlexEvent.CREATION_COMPLETE, onMemberCreationPopUpCreationCompleted);
        }

        //-----------------------------------------------------
        // Access
        //-----------------------------------------------------
        public function get memberCreationPopUp():MemberEditionPopUp {
            return MemberEditionPopUp(viewComponent);
        }

        //-----------------------------------------------------
        // Event handling
        //-----------------------------------------------------
        private function onMemberCreationPopUpCreationCompleted(event:FlexEvent):void {
            memberCreationPopUp.fornameTextInput.addEventListener(Event.CHANGE, onFornameChanged);
            memberCreationPopUp.lastnameTextInput.addEventListener(Event.CHANGE, onLastnameChanged);
            memberCreationPopUp.sizeTextInput.addEventListener(Event.CHANGE, onSizeChanged);
            memberCreationPopUp.birthdayTextInput.addEventListener(Event.CHANGE, onBirthdayChanged);
            memberCreationPopUp.subscriptionDateTextInput.addEventListener(Event.CHANGE, onSubscriptionDateChanged);
            memberCreationPopUp.genderCombo.addEventListener(ListEvent.CHANGE, onGenderChanged);
            memberCreationPopUp.handComboBox.addEventListener(ListEvent.CHANGE, onHandChanged);
            memberCreationPopUp.phoneTextInput.addEventListener(Event.CHANGE, onPhoneNumberChanged);
            memberCreationPopUp.changeAvatarButton.addEventListener(MouseEvent.CLICK, onChangeAvatarButtonClicked);
            // positions
            memberCreationPopUp.leftWingmanCheckBox.addEventListener(MouseEvent.CLICK, onLeftWingmanCheckBoxClicked);
            memberCreationPopUp.rightWingmanCheckBox.addEventListener(MouseEvent.CLICK, onRightWingmanCheckBoxClicked);
            memberCreationPopUp.leftBackcourtCheckBox.addEventListener(MouseEvent.CLICK, onLeftBackcourtCheckBoxClicked);
            memberCreationPopUp.centerBackcourtCheckBox.addEventListener(MouseEvent.CLICK, onCenterBackcourtCheckBoxClicked);
            memberCreationPopUp.rightBackcourtCheckBox.addEventListener(MouseEvent.CLICK, onRightBackcourtCheckBoxClicked);
            memberCreationPopUp.pivotCheckBox.addEventListener(MouseEvent.CLICK, onPivotCheckBoxClicked);
            memberCreationPopUp.guardianCheckBox.addEventListener(MouseEvent.CLICK, onGuardianCheckBoxClicked);

            memberCreationPopUp.cancelButton.addEventListener(MouseEvent.CLICK, onCancelButtonClicked);
            memberCreationPopUp.okButton.addEventListener(MouseEvent.CLICK, onOkButtonClicked);
            initializeView();
        }

        private function onGenderChanged(event:ListEvent):void {
            m_proxy.gender = memberCreationPopUp.genderCombo.selectedItem.value;
            updateAvatar();
        }

        private function onHandChanged(event:ListEvent):void {
            m_proxy.geneticHand = memberCreationPopUp.handComboBox.selectedItem.value;
        }

        private function onFornameChanged(event:Event):void {
            m_proxy.forname = memberCreationPopUp.fornameTextInput.text;
        }

        private function onLastnameChanged(event:Event):void {
            m_proxy.lastname = memberCreationPopUp.lastnameTextInput.text;
        }

        private function onSizeChanged(event:Event):void {
            var sizeTyped:String = memberCreationPopUp.sizeTextInput.text;
            if (sizeTyped.length >= 3) {
                var validationResult:ValidationResultEvent = memberCreationPopUp.sizeValidator.validate();
                if (validationResult.type == ValidationResultEvent.VALID) {
                    m_proxy.size = new Number(sizeTyped);
                } else {
                    m_proxy.size = -1;
                }
            }
        }

        private function onBirthdayChanged(event:Event):void {
            var birthdayTyped:String = memberCreationPopUp.birthdayTextInput.text;
            m_proxy.birthday = getChangedDate(birthdayTyped, memberCreationPopUp.birthdayValidator);
        }

        private function onSubscriptionDateChanged(event:Event):void {
            var subscriptionTyped:String = memberCreationPopUp.subscriptionDateTextInput.text;
            m_proxy.subscriptionDate = getChangedDate(subscriptionTyped, memberCreationPopUp.subscriptionDateValidator);
        }

        private function onPhoneNumberChanged(event:Event):void {
            var phoneNumberTyped:String = memberCreationPopUp.phoneTextInput.text;
            if (phoneNumberTyped.length >= 10) {
                var validationResult:ValidationResultEvent = memberCreationPopUp.phoneValidator.validate();
                if (validationResult.type == ValidationResultEvent.VALID) {
                    m_proxy.phoneNumber = phoneNumberTyped;
                }
            }
        }

        private function onChangeAvatarButtonClicked(event:MouseEvent):void {
            var file:File = new File();
            var fileFilter:FileFilter = new FileFilter("Image", "*.png;*.jpg;*.bmp");

            var fileSelected:Function = function(event:Event):void {
                    m_proxy.avatarPath = file.nativePath;
                    memberCreationPopUp.avatarImage.source = m_proxy.member.avatarPath;
                };

            try {
                file.browseForOpen("Sélectionner une image", [fileFilter]);
                file.addEventListener(Event.SELECT, fileSelected);
            } catch (error:Error) {
                trace("Failed to open file:", error.message);
                return;
            }
        }

        private function onLeftWingmanCheckBoxClicked(event:MouseEvent):void {
            m_proxy.playerActivity.isLeftWingman = memberCreationPopUp.leftWingmanCheckBox.selected;
        }

        private function onRightWingmanCheckBoxClicked(event:MouseEvent):void {
            m_proxy.playerActivity.isRightWingman = memberCreationPopUp.rightWingmanCheckBox.selected;
        }

        private function onLeftBackcourtCheckBoxClicked(event:MouseEvent):void {
            m_proxy.playerActivity.isLeftBackcourt = memberCreationPopUp.leftBackcourtCheckBox.selected;
        }

        private function onCenterBackcourtCheckBoxClicked(event:MouseEvent):void {
            m_proxy.playerActivity.isCenterBackcourt = memberCreationPopUp.centerBackcourtCheckBox.selected;
        }

        private function onRightBackcourtCheckBoxClicked(event:MouseEvent):void {
            m_proxy.playerActivity.isRightBackcourt = memberCreationPopUp.rightBackcourtCheckBox.selected;
        }

        private function onPivotCheckBoxClicked(event:MouseEvent):void {
            m_proxy.playerActivity.isPivot = memberCreationPopUp.pivotCheckBox.selected;
        }

        private function onGuardianCheckBoxClicked(event:MouseEvent):void {
            m_proxy.playerActivity.isGuardian = memberCreationPopUp.guardianCheckBox.selected;
        }

        private function onOkButtonClicked(event:MouseEvent):void {
            if (memberCreationPopUp.lastnameValidated && memberCreationPopUp.fornameValidated && memberCreationPopUp.sizeValidated
                && memberCreationPopUp.birthdayValidated && memberCreationPopUp.inscriptionDateValidated) {
                sendNotification(CloseMemberEditionPopUpCommand.NAME, {"popup": memberCreationPopUp, "member": m_proxy.member});
            }
        }

        private function onCancelButtonClicked(event:MouseEvent):void {
            sendNotification(CloseMemberEditionPopUpCommand.NAME, {"popup": memberCreationPopUp, "member": null});
        }

        //-----------------------------------------------------
        // Implementation
        //-----------------------------------------------------
        private function initializeView():void {
            if (m_proxy.member.forname != null && m_proxy.member.forname.length > 0) {
                memberCreationPopUp.fornameTextInput.text = m_proxy.member.forname;
            }
            if (m_proxy.member.lastname != null && m_proxy.member.lastname.length > 0) {
                memberCreationPopUp.lastnameTextInput.text = m_proxy.member.lastname;
            }
            if (!isNaN(m_proxy.member.size)) {
                memberCreationPopUp.sizeTextInput.text = m_proxy.member.size != -1 ? String(m_proxy.member.size) : "";
            }
            if (m_proxy.member.phoneNumber != null) {
                memberCreationPopUp.phoneTextInput.text = m_proxy.member.phoneNumber;
            }
            memberCreationPopUp.genderCombo.dataProvider = m_proxy.genderList;
            if (m_proxy.member.gender != null) {
                ComboboxUtils.initializeCombo(memberCreationPopUp.genderCombo, "value", m_proxy.member.gender);
            }

            memberCreationPopUp.handComboBox.dataProvider = m_proxy.handList;
            if (m_proxy.member.geneticHand != null) {
                ComboboxUtils.initializeCombo(memberCreationPopUp.handComboBox, "value", m_proxy.member.geneticHand);
            }

            if (m_proxy.member.birthday != null) {
                memberCreationPopUp.birthdayTextInput.text = m_dateFormatter.format(m_proxy.member.birthday);
            }
            if (m_proxy.member.clubEntryDate != null) {
                memberCreationPopUp.subscriptionDateTextInput.text = m_dateFormatter.format(m_proxy.member.clubEntryDate);
            }
            updatePositions();
            updateAvatar();
        }

        private function updatePositions():void {
            if (m_proxy.playerActivity != null) {
                memberCreationPopUp.leftWingmanCheckBox.selected = m_proxy.playerActivity.isLeftWingman;
                memberCreationPopUp.rightWingmanCheckBox.selected = m_proxy.playerActivity.isRightWingman;
                memberCreationPopUp.leftBackcourtCheckBox.selected = m_proxy.playerActivity.isLeftBackcourt;
                memberCreationPopUp.centerBackcourtCheckBox.selected = m_proxy.playerActivity.isCenterBackcourt;
                memberCreationPopUp.rightBackcourtCheckBox.selected = m_proxy.playerActivity.isRightBackcourt;
                memberCreationPopUp.pivotCheckBox.selected = m_proxy.playerActivity.isPivot;
                memberCreationPopUp.guardianCheckBox.selected = m_proxy.playerActivity.isGuardian;
            }
        }

        /**
         * If the member does not have an avatar path, a default picture is loaded
         * If the member have an avatar path, the image is loaded from this one
         */
        private function updateAvatar():void {
            if (m_proxy.member.avatarPath == null) {
                if (m_proxy.member.gender == Person.MALE) {
                    memberCreationPopUp.avatarImage.source = m_manLogo;
                } else if (m_proxy.member.gender == Person.FEMALE) {
                    memberCreationPopUp.avatarImage.source = m_womanLogo;
                }
            } else {
                memberCreationPopUp.avatarImage.source = m_proxy.member.avatarPath
            }
        }

        private function getChangedDate(dateTyped:String, validator:DateValidator):Date {
            if (dateTyped.length >= 10) {
                var validationResult:ValidationResultEvent = validator.validate();
                if (validationResult.type == ValidationResultEvent.VALID) {
                    return parseDate(dateTyped);
                }
            }
            return null;
        }

        private function parseDate(date:String):Date {
            var dateArray:Array = date.split("/");
            return new Date(dateArray[2], Number(dateArray[1]) - 1, dateArray[0]);
        }

    }
}